package com.wl.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.wl.service.AccountService;
import com.wl.vo.Account;

@RestController
public class LoginController {
	
	@Autowired
	private AccountService accountService;
	
    @GetMapping(value={"/"})
    public ModelAndView toLogin(HttpServletRequest req) {
    	HttpSession session = req.getSession();
    	ModelAndView mav = new ModelAndView();
		if (session.getAttribute("userId") == null) {
			mav.setViewName("login");
		} else {
			mav.setViewName("index");
		}
		return mav;
	}
    
    @RequestMapping(value={"/login"})
    public ModelAndView login(Account account, HttpServletRequest req) {
    	HttpSession session = req.getSession();
    	ModelAndView mav = new ModelAndView();
    	
    	if (session.getAttribute("userId") == null) {
    		if (account.getUserName() != null && account.getPassword() != null && accountService.checkAccount(account) != null) {
    			
    			account = accountService.checkAccount(account);
    			session.setAttribute("userId", account.getId());
    			
    			mav.setViewName("index");
    		} else {
    			mav.addObject("error", "用户名密码错误!");
//    		mav.setViewName("login");
    		}
    		
    	} else {
    		mav.setViewName("index");
    	}
    	
    	return mav;
    }
    
    @RequestMapping(value={"/logout"})
    public ModelAndView logout(HttpServletRequest req) {
    	HttpSession session = req.getSession();
    	session.invalidate();
    	
    	ModelAndView mav = new ModelAndView();
    	mav.setViewName("login");
    			
    	return mav;
    }
}
